package linuxbox.calendar.servlet;

import javax.servlet.http.*;
import java.util.*;
import java.sql.*;

import linuxbox.admin.logic.UserManager;
import linuxbox.util.*;
import linuxbox.common.*;

import linuxbox.calendar.logic.*;
import linuxbox.calendar.bean.*;

public class BoxCalendarAction
    extends Action
{
  protected static String viewJSP = null;
  protected static String editJSP = null;

  BoxCalendar home = BoxCalendar.getInstance();

  public void doAction(HttpSession aSession, BoxSession aBoxSession,
                       HttpServletRequest req, HttpServletResponse resp) throws
      Exception
  {
    //The VIEW_FORMAT and currentDate saved in session
    String str = req.getParameter("v");
    if (str != null)
    {
      aSession.setAttribute("calendar.VIEW_FORMAT", str);
    }

    Calendar currentDate = (Calendar) aSession.getAttribute("calendar.CurDate");
    if (currentDate == null)
    {
      currentDate = Calendar.getInstance(aBoxSession.getTimeZone());
      aSession.setAttribute("calendar.CurDate", currentDate);
    }

    str = req.getParameter("t"); //time
    if (str != null)
    {
      long tmp = Long.parseLong(str);
      currentDate.setTime(new java.sql.Date(tmp));
    }

    str = req.getParameter("SORTBY");
    if (str != null)
    {
      aSession.setAttribute("calendar.SORTBY", str);
    }

    str = req.getParameter("ASC");
    if (str != null)
    {
      aSession.setAttribute("calendar.ASC", str);
    }

    str = req.getParameter("LIST_CATEGORY");
    if (str != null)
    {
      aSession.setAttribute("calendar.LIST_CATEGORY", str);
    }

    str = req.getParameter("list");
    if (str != null)
    {
      aSession.setAttribute("calendar.LIST_TYPE", str);
    }

    str = req.getParameter("u"); //time
    if (str != null)
    {
      int tmp = Integer.parseInt(str);
      UserManager um = UserManager.getInstance();
      if (um.getUser(tmp) != null)
        aSession.setAttribute("calendar.CurCalUserID", str);
      else
        sendError("No user found for id:"+str, req, resp);
    }
    else
    {
        str = (String) aSession.getAttribute("calendar.CurCalUserID");
        if (str == null)
          aSession.setAttribute("calendar.CurCalUserID", String.valueOf(aBoxSession.getID()));
    }

    str = req.getParameter("SubmitCancel");
    if (str != null)
    {
      sendFile(viewJSP, req, resp);
      return;
    }

    int curEntryID = 0;
    str = req.getParameter("id");
    if (str != null)
    {
      curEntryID = Integer.parseInt(str);
    }
    str = (String) req.getParameter("SubmitSave");
    if (str != null)
    {
      saveToBean(curEntryID, req, aBoxSession);
      sendFile(viewJSP, req, resp);
      return;
    }
    str = req.getParameter("SubmitUpdate");
    if (str != null)
    {
      saveToBean(curEntryID, req, aBoxSession);
      sendFile(viewJSP, req, resp);
      return;
    }
    str = req.getParameter("SubmitSearch");
    if (str != null)
    {
      setSearchAttributes(req);
      sendFile(viewJSP, req, resp);
      return;
    }
    str = req.getParameter("SubmitDelete");
    if (str != null)
    {
      deleteBean(req, curEntryID);
      sendFile(viewJSP, req, resp);
      return;
    }
    str = req.getParameter("SubmitEdit");
    if (str != null)
    {
      // Now we'll go to the edit form
      if (curEntryID == 0)
      {
        setEntryDefaultAttributes(req);
      }
      else
      {
        setEntryAttributes(req, aBoxSession, curEntryID);
      }
      sendFile(editJSP, req, resp);
      return;
    }
    sendFile(viewJSP, req, resp);
  }

  protected void saveToBean(int id, HttpServletRequest req, BoxSession aBoxSession)
  {
    int curUserID = aBoxSession.getID();
    BoxCalendarEntry bean = null;
    if (id == 0)
    {
      bean = home.add(curUserID);
    }
    else
    {
      bean = home.get(id, curUserID);
    }
    if (bean == null)
    {
      return;
    }

    String str = req.getParameter("SUBJECT");
    if (str != null && str.length() > 0)
    {
      bean.setSubject(str);
    }
    else
    {
      bean.setSubject("No title");

    }
    str = req.getParameter("DESCRIPTION");
    if (str != null)
    {
      bean.setDescription(str);

    }
    str = req.getParameter("CATEGORY");
    if (str != null)
    {
      bean.setCategory(str);
    }

    str = req.getParameter("SHARING");
    if (str != null)
    {
      bean.setSharing(Integer.parseInt(str));
    }

    str = req.getParameter("ISALLDAY");
    if (str != null)
    {
      bean.setIsAllDay(Integer.parseInt(str) > 0);
    }

    Calendar tmpCal = Calendar.getInstance(aBoxSession.getTimeZone());
    int tmpYear = tmpCal.get(Calendar.YEAR);
    int tmpMonth = tmpCal.get(Calendar.MONTH);
    int tmpDay = tmpCal.get(Calendar.DAY_OF_MONTH);
    int tmpHour = tmpCal.get(Calendar.HOUR_OF_DAY);
    int tmpMinute = tmpCal.get(Calendar.MINUTE);

    str = req.getParameter("FROM_YEAR");
    if (str != null)
    {
      tmpYear = Integer.parseInt(str);
    }
    str = req.getParameter("FROM_MONTH");
    if (str != null)
    {
      tmpMonth = Integer.parseInt(str);
    }
    str = req.getParameter("FROM_DAY");
    if (str != null)
    {
      tmpDay = Integer.parseInt(str);
    }
    str = req.getParameter("FROM_HOUR");
    if (str != null)
    {
      tmpHour = Integer.parseInt(str);
    }
    str = req.getParameter("FROM_MINUTE");
    if (str != null)
    {
      tmpMinute = Integer.parseInt(str);
    }
    tmpCal.set(tmpYear, tmpMonth, tmpDay, tmpHour, tmpMinute, 0);
    bean.setFromTime(new Timestamp(tmpCal.getTime().getTime()));

    str = req.getParameter("DURATION_HOUR");
    if (str != null)
    {
      tmpHour = Integer.parseInt(str);
    }
    else
    {
      tmpHour = 0;

    }
    str = req.getParameter("DURATION_MINUTE");
    if (str != null)
    {
      tmpMinute = Integer.parseInt(str);
    }
    else
    {
      tmpMinute = 0;
    }
    tmpCal.add(Calendar.HOUR_OF_DAY, tmpHour);
    tmpCal.add(Calendar.MINUTE, tmpMinute);
    if (tmpDay != tmpCal.get(Calendar.DAY_OF_MONTH))
    {
      tmpCal.set(Calendar.DAY_OF_MONTH, tmpDay);
      tmpCal.set(Calendar.HOUR_OF_DAY, 23);
      tmpCal.set(Calendar.MINUTE, 59);
    }
    bean.setToTime(new Timestamp(tmpCal.getTime().getTime()));

    BoxCalendarRepeat repeat = null;
    str = req.getParameter("REPEAT_TYPE");
    int tmp = 0;
    if (str != null)
    {
      tmp = Integer.parseInt(str);
    }
    if (tmp == 0)
    {
      bean.setRepeat(false);
    }
    else
    {
      bean.setRepeat(true);
      /*
        BY_WEEK = 1;
        BY_WEEK_OF_MONTH = 2;
        BY_MONTH = 3;
        BY_YEAR  = 4;
       */
      repeat = new BoxCalendarRepeat();
      repeat.setID(bean.getID());
      repeat.setType(tmp);
      switch (tmp)
      {
        case BoxCalendarRepeat.BY_WEEK:
          str = req.getParameter("REPEAT_EVERYWEEK");
          if (str != null)
          {
            repeat.setEvery(Integer.parseInt(str));
          }
          else
          {
            repeat.setEvery(1);

          }
          String days[] = req.getParameterValues("REPEAT_WEEKDAYS");
          tmp = 0;
          for (int i = 0; i < days.length; i++)
          {
            tmp |= Integer.parseInt(days[i]);
          }
          repeat.setDayOfWeek(tmp);
          break;
        case BoxCalendarRepeat.BY_WEEK_OF_MONTH:
          str = req.getParameter("REPEAT_EVERYMONTH");
          if (str != null)
          {
            repeat.setEvery(Integer.parseInt(str));
          }
          else
          {
            repeat.setEvery(1);

          }
          str = req.getParameter("REPEAT_WHICHWEEKDAY");
          if (str != null)
          {
            repeat.setDayOfWeek(Integer.parseInt(str));

          }
          str = req.getParameter("REPEAT_WHICHWEEK");
          if (str != null)
          {
            repeat.setWhichDay(Integer.parseInt(str));
          }
          break;
        case BoxCalendarRepeat.BY_MONTH:
        case BoxCalendarRepeat.BY_YEAR:
          break;
      }
    }
    String[] strInvitedUsers = req.getParameterValues("INVITED_USERS");
    int[] intInvitedUsers = null;
    if (strInvitedUsers != null && strInvitedUsers.length > 0)
    {
      intInvitedUsers = new int[strInvitedUsers.length];
      for(int i = 0; i < intInvitedUsers.length; i++)
        intInvitedUsers[i] = Integer.parseInt(strInvitedUsers[i]);
    }

    home.update(bean, repeat, intInvitedUsers);
  }

  protected void deleteBean(HttpServletRequest req, int id)
  {
    int curUserID = WebTools.getBoxSession(req).getID();
    if (id != 0 && curUserID != -1)
    {
      home.remove(id, curUserID);
    }
  }

  protected void setSearchAttributes(HttpServletRequest req)
  {
    req.setAttribute("VIEW_FORMAT", "search");
    HttpSession session = req.getSession();
    String tmp = (String) req.getParameter("SEARCH_WORDS");
    if (tmp == null)
    {
      session.setAttribute("SEARCH_WORDS", "");
    }
    else
    {
      session.setAttribute("SEARCH_WORDS", tmp.trim());
    }

    tmp = (String) req.getParameter("SEARCH_BY_TITLE");
    if (tmp != null)
    {
      session.setAttribute("SEARCH_BY_TITLE", tmp);
    }
    else
    {
      session.setAttribute("SEARCH_BY_TITLE", "0");
    }

    tmp = (String) req.getParameter("SEARCH_BY_DESC");
    if (tmp != null)
    {
      session.setAttribute("SEARCH_BY_DESC", tmp);
    }
    else
    {
      session.setAttribute("SEARCH_BY_DESC", "0");
    }

    tmp = (String) req.getParameter("SEARCH_CATEGORY");
    if (tmp != null)
    {
      session.setAttribute("SEARCH_CATEGORY", tmp);
    }
    else
    {
      session.setAttribute("SEARCH_CATEGORY", "");
    }
  }

  protected void setEntryAttributes(HttpServletRequest req, BoxSession aBoxSession, int beanID)
  {
    int curUserID = Integer.parseInt((String)req.getSession().getAttribute("calendar.CurCalUserID"));
    BoxCalendarEntryKey key = new BoxCalendarEntryKey(beanID, curUserID);
    BoxCalendarEntry bean = home.get(key);
    if (bean == null)
    {
      setEntryDefaultAttributes(req);
      return;
    }

    //Set the defalut attributes for a new entry
    req.setAttribute("ID", new Integer(bean.getID()).toString());
    req.setAttribute("SUBJECT", bean.getSubject());

    //TODO: add Taglib default to "Meeting"
    req.setAttribute("CATEGORY", bean.getCategory());
    req.setAttribute("SHARING", new Integer(bean.getSharing()).toString());
    req.setAttribute("ISALLDAY", (bean.getIsAllDay() ? "1" : "0"));

    Calendar tmpCal = Calendar.getInstance(aBoxSession.getTimeZone());
    tmpCal.setTime(bean.getFromTime());
    req.setAttribute("FROM_YEAR",
                     new Integer(tmpCal.get(Calendar.YEAR)).toString());
    req.setAttribute("FROM_MONTH",
                     new Integer(tmpCal.get(Calendar.MONTH)).toString());
    req.setAttribute("FROM_DAY",
                     new Integer(tmpCal.get(Calendar.DAY_OF_MONTH)).toString());
    req.setAttribute("FROM_HOUR",
                     new Integer(tmpCal.get(Calendar.HOUR_OF_DAY)).toString());
    req.setAttribute("FROM_MINUTE",
                     new Integer(tmpCal.get(Calendar.MINUTE)).toString());
    long tmpLong = bean.getToTime().getTime();
    tmpLong -= bean.getFromTime().getTime();
    req.setAttribute("DURATION_HOUR",
                     new Integer( (int) (tmpLong / (1000 * 60 * 60))).toString());
    tmpLong = (tmpLong % (1000 * 60 * 60)) / (1000 * 60);
    req.setAttribute("DURATION_MINUTE", new Integer( (int) tmpLong).toString());

    req.setAttribute("DESCRIPTION", bean.getDescription());
    req.setAttribute("CREATEDBY", String.valueOf(bean.getCreatedBy()));
    req.setAttribute("INVITED_USERS", home.getInvitedUsers(bean));

    if (bean.getRepeat())
    {
      BoxCalendarRepeat repeatBean = home.getRepeat(key);
      req.setAttribute("REPEAT_TYPE",
                       new Integer(repeatBean.getType()).toString());
      req.setAttribute("REPEAT_EVERYWEEK",
                       new Integer(repeatBean.getEvery()).toString());
      req.setAttribute("REPEAT_WEEKDAYS",
                       new Integer(repeatBean.getDayOfWeek()).toString());
      req.setAttribute("REPEAT_WHICHWEEK",
                       new Integer(repeatBean.getWhichDay()).toString());
      req.setAttribute("REPEAT_WHICHWEEKDAY",
                       new Integer(repeatBean.getDayOfWeek()).toString());
      req.setAttribute("REPEAT_EVERYMONTH",
                       new Integer(repeatBean.getEvery()).toString());
      if (repeatBean.getUntilTime() == null)
      {
        req.setAttribute("REPEAT_FOREVER", "1");
        req.setAttribute("UNTIL_YEAR",
                         new Integer(tmpCal.get(Calendar.YEAR) + 1).toString());
        req.setAttribute("UNTIL_MONTH",
                         new Integer(tmpCal.get(Calendar.MONTH)).toString());
        req.setAttribute("UNTIL_DAY",
                         new Integer(tmpCal.get(Calendar.DAY_OF_MONTH)).
                         toString());
      }
      else
      {
        tmpCal.setTime(repeatBean.getUntilTime());
        req.setAttribute("REPEAT_FOREVER", "0");
        req.setAttribute("UNTIL_YEAR",
                         new Integer(tmpCal.get(Calendar.YEAR) + 1).toString());
        req.setAttribute("UNTIL_MONTH",
                         new Integer(tmpCal.get(Calendar.MONTH)).toString());
        req.setAttribute("UNTIL_DAY",
                         new Integer(tmpCal.get(Calendar.DAY_OF_MONTH)).
                         toString());
      }
    }
    else
    {
      req.setAttribute("REPEAT_TYPE", "0");
      req.setAttribute("REPEAT_EVERYWEEK", "0");
      req.setAttribute("REPEAT_WEEKDAYS", "0");
      req.setAttribute("REPEAT_WHICHWEEK", "1");
      req.setAttribute("REPEAT_WHICHWEEKDAY", "1");
      req.setAttribute("REPEAT_EVERYMONTH", "1");

      req.setAttribute("REPEAT_FOREVER", "1");
      req.setAttribute("UNTIL_YEAR",
                       new Integer(tmpCal.get(Calendar.YEAR) + 1).toString());
      req.setAttribute("UNTIL_MONTH",
                       new Integer(tmpCal.get(Calendar.MONTH)).toString());
      req.setAttribute("UNTIL_DAY",
                       new Integer(tmpCal.get(Calendar.DAY_OF_MONTH)).toString());

    }
  }

  protected void setEntryDefaultAttributes(HttpServletRequest req)
  {
    //Set the defalut attributes for a new entry
    req.setAttribute("ID", "0");
    req.setAttribute("SUBJECT", "");

    //TODO: add Taglib default to "Meeting"
//		req.setAttribute("CATEGORY", "16");
    String str = req.getParameter("CATEGORY"); //time
    if (str != null)
    {
      req.setAttribute("CATEGORY", str);
    }

    HttpSession session = req.getSession();
    Calendar tmpCal = (Calendar) session.getAttribute("calendar.CurDate");
    req.setAttribute("FROM_YEAR",
                     new Integer(tmpCal.get(Calendar.YEAR)).toString());
    req.setAttribute("FROM_MONTH",
                     new Integer(tmpCal.get(Calendar.MONTH)).toString());
    req.setAttribute("FROM_DAY",
                     new Integer(tmpCal.get(Calendar.DAY_OF_MONTH)).toString());
    req.setAttribute("FROM_HOUR", "8");
    req.setAttribute("FROM_MINUTE", "0");
    req.setAttribute("FROM_HOUR",
                     new Integer(tmpCal.get(Calendar.HOUR_OF_DAY)).toString());
    req.setAttribute("FROM_MINUTE",
                     new Integer(tmpCal.get(Calendar.MINUTE)).toString());
    req.setAttribute("DURATION_HOUR", "1");
    req.setAttribute("DURATION_MINUTE", "0");
    req.setAttribute("SHARING", "1");
    req.setAttribute("ISALLDAY", "0");

    req.setAttribute("DESCRIPTION", "");
    req.setAttribute("CREATEDBY", String.valueOf(WebTools.getBoxSession(req).getID()));
    req.setAttribute("INVITED_USERS", null);

    req.setAttribute("REPEAT_TYPE", "0");
    req.setAttribute("REPEAT_EVERYWEEK", "0");
    req.setAttribute("REPEAT_WEEKDAYS", "0");
    req.setAttribute("REPEAT_WHICHWEEK", "1");
    req.setAttribute("REPEAT_WHICHWEEKDAY", "1");
    req.setAttribute("REPEAT_EVERYMONTH", "1");

    req.setAttribute("REPEAT_FOREVER", "1");
    req.setAttribute("UNTIL_YEAR", String.valueOf((tmpCal.get(Calendar.YEAR) + 1)));
    req.setAttribute("UNTIL_MONTH", String.valueOf(tmpCal.get(Calendar.MONTH)));
    req.setAttribute("UNTIL_DAY", String.valueOf(tmpCal.get(Calendar.DAY_OF_MONTH)));
  }

  public void setViewJSP(String str)
  {
    viewJSP = str;
  }

  public void setEditJSP(String str)
  {
    editJSP = str;
  }
}
